/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.synchronization.remote.ws;

import java.util.Iterator;
import systole.domain.analysis.Analysis;
import systole.domain.clinicalInformation.ClinicalInformation;
import systole.domain.clinicalInformation.Family;
import systole.domain.clinicalInformation.Medicine;
import systole.domain.clinicalInformation.Pathology;
import systole.domain.clinicalInformation.Sport;
import systole.domain.clinicalInformation.Surgery;
import systole.domain.persons.Medic;
import systole.domain.persons.Patient;
import systole.domain.persons.identityCard.IdentityCardType;
import systole.domain.persons.profession.Profession;
import systole.domain.signals.SignalFrequency;
import systole.exceptions.ExceptionDAO;
import systole.exceptions.ExceptionWS;
import systole.ioHandling.logs.SystoleLogger;
import systole.persistence.FacadeDB;
import systole.synchronization.remote.entities.AnalysisRemote;
import systole.synchronization.remote.entities.ClinicalInfoRemote;
import systole.synchronization.remote.entities.FamilyRemote;
import systole.synchronization.remote.entities.IdentityCardTypeRemote;
import systole.synchronization.remote.entities.MedicRemote;
import systole.synchronization.remote.entities.MedicineRemote;
import systole.synchronization.remote.entities.PathologyRemote;
import systole.synchronization.remote.entities.PatientRemote;
import systole.synchronization.remote.entities.ProfessionRemote;
import systole.synchronization.remote.entities.SignalFrequencyRemote;
import systole.synchronization.remote.entities.SportRemote;
import systole.synchronization.remote.entities.SurgeryRemote;
import systole.synchronization.remote.ws.converter.ConverterToLocalEntity;
import systole.synchronization.remote.ws.converter.ConverterToRemoteEntity;

/**
 *
 * @author jmj
 */
public class SystoleSyncWS {

    private SystoleSync systoleSync;
    private FacadeDB facadeDB;
    private SystoleLogger log;
    private ConverterToLocalEntity toLocalEntity;
    private ConverterToRemoteEntity toRemoteEntity;

    public SystoleSyncWS() {
        super();
        this.facadeDB = FacadeDB.getInstance();
        this.log = SystoleLogger.getInstance();
        this.toLocalEntity = new ConverterToLocalEntity();
        this.toRemoteEntity = new ConverterToRemoteEntity();
    }

    public void connectToWS() throws ExceptionWS {
        try {
            this.log.logDebug("Connecting to WS");
            SystoleSync_Service service = new SystoleSync_Service();
            this.systoleSync = service.getSystoleSyncSOAP();
        } catch (Exception ex) {
            this.log.logError("Error on connect to ws, msg: " + ex.getMessage());
            throw new ExceptionWS("No se pudo establecer la conexión con el servidor");
        }

    }

    public boolean uploadPatients() {
        try {
            this.log.logDebug("Start to upload patients");
            Iterator<Patient> patientsToUpload = this.facadeDB.getPatientSyncBroker().getPatientsToUpload().iterator();
            while (patientsToUpload.hasNext()) {
                Patient patient = patientsToUpload.next();
                PatientWs patientWs = this.toRemoteEntity.generateRemotePatient(patient);
                if (patientWs != null) {
                    int remoteId = this.systoleSync.uploadPatient(patientWs);
                    if (remoteId > 0) {
                        PatientRemote patientRemote = new PatientRemote(patient);
                        patientRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getPatientSyncBroker().savePatientRemote(patientRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Patients upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload patients aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload patients aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadMedics() {
        try {
            this.log.logDebug("Start to upload medics");
            Iterator<Medic> medicsToUpload = this.facadeDB.getMedicSyncBroker().getMedicsToUpload().iterator();
            while (medicsToUpload.hasNext()) {
                Medic medic = medicsToUpload.next();
                MedicWs medicWs = this.toRemoteEntity.generateRemoteMedic(medic);
                if (medicWs != null) {
                    int remoteId = this.systoleSync.uploadMedic(medicWs);
                    if (remoteId > 0) {
                        MedicRemote medicRemote = new MedicRemote(medic);
                        medicRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getMedicSyncBroker().saveMedicRemote(medicRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Medics upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload medics aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload medics aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadMedicines() {
        try {
            this.log.logDebug("Start to upload medicines");
            Iterator<Medicine> medicinesToUpload = this.facadeDB.getMedicineSyncBroker().getMedicinesToUpload().iterator();
            while (medicinesToUpload.hasNext()) {
                Medicine medicine = medicinesToUpload.next();
                MedicineWs medicineWs = this.toRemoteEntity.generateRemoteMedicine(medicine);
                if (medicineWs != null) {
                    int remoteId = this.systoleSync.uploadMedicine(medicineWs);
                    if (remoteId > 0) {
                        MedicineRemote medicineRemote = new MedicineRemote(medicine);
                        medicineRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getMedicineSyncBroker().saveMedicineRemote(medicineRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Medicines upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload medicines aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload medicines aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadPathologies() {
        try {
            this.log.logDebug("Start to upload Pathologies");
            Iterator<Pathology> pathologiesToUpload = this.facadeDB.getPathologySyncBroker().getPathologiesToUpload().iterator();
            while (pathologiesToUpload.hasNext()) {
                Pathology pathology = pathologiesToUpload.next();
                PathologyWs pathologyWs = this.toRemoteEntity.generateRemotePathology(pathology);
                if (pathologyWs != null) {
                    int remoteId = this.systoleSync.uploadPathology(pathologyWs);
                    if (remoteId > 0) {
                        PathologyRemote pathologyRemote = new PathologyRemote(pathology);
                        pathologyRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getPathologySyncBroker().savePathologyRemote(pathologyRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Pathologies upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload pathologies aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload pathologies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadSports() {
        try {
            this.log.logDebug("Start to upload Sports");
            Iterator<Sport> sportsToUpload = this.facadeDB.getSportSyncBroker().getSportsToUpload().iterator();
            while (sportsToUpload.hasNext()) {
                Sport sport = sportsToUpload.next();
                SportWs sportWs = this.toRemoteEntity.generateRemoteSport(sport);
                if (sportWs != null) {
                    int remoteId = this.systoleSync.uploadSport(sportWs);
                    if (remoteId > 0) {
                        SportRemote sportRemote = new SportRemote(sport);
                        sportRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getSportSyncBroker().saveSportRemote(sportRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Sports upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload sports aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload sports aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadSignalFrequency() {
        try {
            this.log.logDebug("Start to upload freguencies");
            Iterator<SignalFrequency> signalFrequenciesToUpload = this.facadeDB.getSignalFrequencySyncBroker().getSignalFrequenciesToUpload().iterator();
            while (signalFrequenciesToUpload.hasNext()) {
                SignalFrequency frequency = signalFrequenciesToUpload.next();
                SignalFrequencyWs signalFrequencyWs = this.toRemoteEntity.generateRemoteSignalFrequency(frequency);
                if (signalFrequencyWs != null) {
                    int remoteId = this.systoleSync.uploadSignalFrequency(signalFrequencyWs);
                    if (remoteId > 0) {
                        SignalFrequencyRemote signalFrequencyRemote = new SignalFrequencyRemote(frequency);
                        signalFrequencyRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getSignalFrequencySyncBroker().saveSignalFrequencyRemote(signalFrequencyRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Freguencies upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload freguencies aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload freguencies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadSurgeries() {
        try {
            this.log.logDebug("Start to upload Surgeries");
            Iterator<Surgery> surgeriesToUpload = this.facadeDB.getSurgerySyncBroker().getSurgeriesToUpload().iterator();
            while (surgeriesToUpload.hasNext()) {
                Surgery surgery = surgeriesToUpload.next();
                SurgeryWs surgeryWs = this.toRemoteEntity.generateRemoteSurgery(surgery);
                if (surgeryWs != null) {
                    int remoteId = this.systoleSync.uploadSurgery(surgeryWs);
                    if (remoteId > 0) {
                        SurgeryRemote surgeryRemote = new SurgeryRemote(surgery);
                        surgeryRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getSurgerySyncBroker().saveSurgeryRemote(surgeryRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Surgeries upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload surgeries aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload surgeries aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadAnalysis() {
        try {
            this.log.logDebug("Start to upload Analysis");
            Iterator<Analysis> familyToUpload = this.facadeDB.getAnalysisSyncBroker().getAnalysisToUpload().iterator();
            while (familyToUpload.hasNext()) {
                Analysis analysis = familyToUpload.next();
                AnalysisWs analysisWs = this.toRemoteEntity.generateRemoteAnalysis(analysis);
                if (analysisWs != null) {
                    int remoteId = this.systoleSync.uploadAnalysis(analysisWs);
                    if (remoteId > 0) {
                        AnalysisRemote analysisRemote = new AnalysisRemote(analysis);
                        analysisRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getAnalysisSyncBroker().saveAnalysisRemote(analysisRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Analysis upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload Analysis aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload Analysis aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadFamily() {
        try {
            this.log.logDebug("Start to upload Family");
            Iterator<Family> familyToUpload = this.facadeDB.getFamilySyncBroker().getFamiliesToUpload().iterator();
            while (familyToUpload.hasNext()) {
                Family family = familyToUpload.next();
                FamilyWs familyWs = this.toRemoteEntity.generateRemoteFamily(family);
                if (familyWs != null) {
                    int remoteId = this.systoleSync.uploadFamily(familyWs);
                    if (remoteId > 0) {
                        FamilyRemote familyRemote = new FamilyRemote(family);
                        familyRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getFamilySyncBroker().saveFamilyRemote(familyRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Family upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload Family aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload Family aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadClinicalInfo() {
        try {
            this.log.logDebug("Start to upload clinical info");
            Iterator<ClinicalInformation> clinicalInfoToUpload = this.facadeDB.getClinicalInfoSyncBroker().getClinicalInfoToUpload().iterator();
            while (clinicalInfoToUpload.hasNext()) {
                ClinicalInformation clinicalInformation = clinicalInfoToUpload.next();
                ClinicalInfoWs clinicalInfoWs = this.toRemoteEntity.generateRemoteClinicalInformation(clinicalInformation);
                if (clinicalInfoWs != null) {
                    int remoteId = this.systoleSync.uploadClinicalInformation(clinicalInfoWs);
                    if (remoteId > 0) {
                        ClinicalInfoRemote clinicalInfoRemote = new ClinicalInfoRemote(clinicalInformation);
                        clinicalInfoRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getClinicalInfoSyncBroker().saveClinicalInfoRemote(clinicalInfoRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("clinical info upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload clinical info aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload clinical info aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadIdentityCardType() {
        try {
            this.log.logDebug("Start to upload identity card types");
            Iterator<IdentityCardType> cardTypesToUpload = this.facadeDB.getIdentityCardTypeSyncBroker().getIdentityCardTypeToUpload().iterator();
            while (cardTypesToUpload.hasNext()) {
                IdentityCardType cardType = cardTypesToUpload.next();
                IdentityCardTypeWs cardTypeWs = this.toRemoteEntity.generateRemoteIdentityCard(cardType);
                if (cardTypeWs != null) {
                    int remoteId = this.systoleSync.uploadIdentityCardType(cardTypeWs);
                    if (remoteId > 0) {
                        IdentityCardTypeRemote cardTypeRemote = new IdentityCardTypeRemote(cardType);
                        cardTypeRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getIdentityCardTypeSyncBroker().saveIdentityCardTypeRemote(cardTypeRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("identity card types upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload identity card types aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload identity card types aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean uploadProfessions() {
        try {
            this.log.logDebug("Start to upload professions");
            Iterator<Profession> professionsToUpload = this.facadeDB.getProfessionSyncBroker().getProfessionsToUpload().iterator();
            while (professionsToUpload.hasNext()) {
                Profession profession = professionsToUpload.next();
                ProfessionWs professionWs = this.toRemoteEntity.generateRemoteProfessionRemote(profession);
                if (professionWs != null) {
                    int remoteId = this.systoleSync.uploadProfession(professionWs);
                    if (remoteId > 0) {
                        ProfessionRemote professionRemote = new ProfessionRemote(profession);
                        professionRemote.setRemoteId(remoteId);
                        FacadeDB.getInstance().startTransaction();
                        FacadeDB.getInstance().getProfessionSyncBroker().saveProfessionRemote(professionRemote);
                        FacadeDB.getInstance().commitTransaction();
                    }
                }
            }
            this.log.logDebug("Professions upload finished");
        } catch (ExceptionDAO edao) {
            this.log.logError("Upload professions aborted, " + edao.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Upload professions aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadPatients() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getPatientSyncBroker().getLastRemotePatientIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download patients");
        try {
            PatientsPage page = this.systoleSync.downloadPatients(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getPatients() != null)) {
                Iterator<PatientWs> patients = page.getPatients().iterator();
                while (patients.hasNext()) {
                    this.toLocalEntity.savePatient(patients.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getPatientSyncBroker().getLastRemotePatientIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadPatients(lastEntitySyncronized);
            }
            this.log.logDebug("Patients download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download patient aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download patient aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadMedics() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getMedicSyncBroker().getLastRemoteMedicIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download medics");
        try {
            MedicsPage page = this.systoleSync.downloadMedics(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getMedics() != null)) {
                Iterator<MedicWs> medics = page.getMedics().iterator();
                while (medics.hasNext()) {
                    this.toLocalEntity.saveMedic(medics.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getMedicSyncBroker().getLastRemoteMedicIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadMedics(lastEntitySyncronized);
            }
            this.log.logDebug("Medics download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download medics aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download medics aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadMedicines() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getMedicineSyncBroker().getLastRemoteMedicineIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download medicines");
        try {
            MedicinesPage page = this.systoleSync.downloadMedicines(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getMedicines() != null)) {
                Iterator<MedicineWs> medicines = page.getMedicines().iterator();
                while (medicines.hasNext()) {
                    this.toLocalEntity.saveMedicine(medicines.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getMedicineSyncBroker().getLastRemoteMedicineIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadMedicines(lastEntitySyncronized);
            }
            this.log.logDebug("Medicines download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download medicines aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download medicines aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadPathologies() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getPathologySyncBroker().getLastRemotePathologyIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download pathologies");
        try {
            PathologiesPage page = this.systoleSync.downloadPathologies(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getPathologies() != null)) {
                Iterator<PathologyWs> pathologies = page.getPathologies().iterator();
                while (pathologies.hasNext()) {
                    this.toLocalEntity.savePathology(pathologies.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getPathologySyncBroker().getLastRemotePathologyIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadPathologies(lastEntitySyncronized);
            }
            this.log.logDebug("Pathologies download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download pathologies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download pathologies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadSports() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getSportSyncBroker().getLastRemoteSportIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download sports");
        try {
            SportsPage page = this.systoleSync.downloadSports(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getSports() != null)) {
                Iterator<SportWs> sports = page.getSports().iterator();
                while (sports.hasNext()) {
                    this.toLocalEntity.saveSport(sports.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getSportSyncBroker().getLastRemoteSportIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadSports(lastEntitySyncronized);
            }
            this.log.logDebug("Sports download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download sports aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download sports aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadClinicalInfo() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getClinicalInfoSyncBroker().getLastRemoteClinicalInfoIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to clinical info ");
        try {
            ClinicalInfoPage page = this.systoleSync.downloadClinicalInformation(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getClinicalInfoList() != null)) {
                Iterator<ClinicalInfoWs> clinicalInfoIt = page.getClinicalInfoList().iterator();
                while (clinicalInfoIt.hasNext()) {
                    this.toLocalEntity.saveClinicalInfo(clinicalInfoIt.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getClinicalInfoSyncBroker().getLastRemoteClinicalInfoIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadClinicalInformation(lastEntitySyncronized);
            }
            this.log.logDebug("clinical info download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download clinical info aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download clinical info aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadSignalFrequency() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getSignalFrequencySyncBroker().getLastRemoteSignalFrequencyIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download signal frequencies");
        try {
            SignalFrequencyPage page = this.systoleSync.downloadSignalFrequency(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getFrequencies() != null)) {
                Iterator<SignalFrequencyWs> signalFrequencies = page.getFrequencies().iterator();
                while (signalFrequencies.hasNext()) {
                    this.toLocalEntity.saveSignalFrequency(signalFrequencies.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getSignalFrequencySyncBroker().getLastRemoteSignalFrequencyIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadSignalFrequency(lastEntitySyncronized);
            }
            this.log.logDebug("Signal Frequencies download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download signal frequencies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download signal frequencies aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadSurgeries() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getSurgerySyncBroker().getLastRemoteSurgeryIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download surgeries");
        try {
            SurgeriesPage page = this.systoleSync.downloadSurgeries(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getSurgeries() != null)) {
                Iterator<SurgeryWs> surgeries = page.getSurgeries().iterator();
                while (surgeries.hasNext()) {
                    this.toLocalEntity.saveSurgery(surgeries.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getSurgerySyncBroker().getLastRemoteSurgeryIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadSurgeries(lastEntitySyncronized);
            }
            this.log.logDebug("Surgeries download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download surgeries aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download surgeries aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadAnalysis() {
        return false;
    }

    public boolean downloadFamily() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getFamilySyncBroker().getLastRemoteFamilyIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download family");
        try {
            FamilyPage page = this.systoleSync.downloadFamily(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getFamily() != null)) {
                Iterator<FamilyWs> family = page.getFamily().iterator();
                while (family.hasNext()) {
                    this.toLocalEntity.saveFamily(family.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getFamilySyncBroker().getLastRemoteFamilyIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadFamily(lastEntitySyncronized);
            }
            this.log.logDebug("Family download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download family aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download family aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadIdentityCardType() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getIdentityCardTypeSyncBroker().getLastRemotIdentityCardTypeIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download identity card types");
        try {
            IdentityCardsPage page = this.systoleSync.downloadIdentityCardTypes(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getIdentityCards() != null)) {
                Iterator<IdentityCardTypeWs> identityCardIt = page.getIdentityCards().iterator();
                while (identityCardIt.hasNext()) {
                    this.toLocalEntity.saveIdentityCardType(identityCardIt.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getIdentityCardTypeSyncBroker().getLastRemotIdentityCardTypeIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadIdentityCardTypes(lastEntitySyncronized);
            }
            this.log.logDebug("Identity card types download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download identity card types aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download  identity card aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean downloadAverages() {
        this.log.logDebug("Stating to download averages");
        try {
            AveragesWs averages = this.systoleSync.downloadAverages();
            this.toLocalEntity.saveAverages(averages);
            this.log.logDebug("Averages download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download averages aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download averages aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;

    }

    public boolean downloadProfessions() throws ExceptionDAO {
        int lastId = FacadeDB.getInstance().getProfessionSyncBroker().getLastRemoteProfessionIdSynchronized();
        LastEntitySyncronized lastEntitySyncronized = new LastEntitySyncronized();
        lastEntitySyncronized.setRemoteId(lastId);
        this.log.logDebug("Stating to download professions");
        try {
            ProfessionsPage page = this.systoleSync.downloadProfessions(lastEntitySyncronized);
            while ((page != null) && (page.getMaxId() > 0) && (page.getProfessions() != null)) {
                Iterator<ProfessionWs> professionsIt = page.getProfessions().iterator();
                while (professionsIt.hasNext()) {
                    this.toLocalEntity.saveProfession(professionsIt.next());
                }
                int lastValueId = lastId;
                lastId = FacadeDB.getInstance().getProfessionSyncBroker().getLastRemoteProfessionIdSynchronized();
                if (lastId == lastValueId) {
                    // si levanta siempre el mismo entra en ciclo infinito
                    return true;
                }
                lastEntitySyncronized = new LastEntitySyncronized();
                lastEntitySyncronized.setRemoteId(lastId);
                page = this.systoleSync.downloadProfessions(lastEntitySyncronized);
            }
            this.log.logDebug("professions download finished");
        } catch (ExceptionDAO e) {
            this.log.logError("Download professions aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        } catch (Exception e) {
            this.log.logError("Download professions aborted, " + e.getMessage());
            FacadeDB.getInstance().refreshSession();
            return false;
        }
        return true;
    }

    public boolean mergePatients() {
        return true;
    }

    public boolean mergeMedics() {
        return true;
    }

    public boolean mergeMedicines() {
        return true;
    }

    public boolean mergePathologies() {
        return true;
    }

    public boolean mergeSports() {
        return true;
    }

    public boolean mergeSignalFrequency() {
        return true;
    }

    public boolean mergeSurgeries() {
        return true;
    }

    public boolean mergeAnalysis() {
        return true;
    }

    public boolean mergeFamily() {
        return true;
    }

    public boolean mergeIdentityCardType() {
        return true;
    }

    public boolean mergeClinicalInfo() {
        return true;
    }

    public boolean mergeProfessions() {
        return true;
    }
}
